/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TrabRmPanel.java
 *
 * Created on 29/11/2011, 22:26:41
 */

package proj5labbd.graphics.trabalho;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class TrabRmPanel extends OperationPanel {

    /** Creates new form TrabRmPanel */
    public TrabRmPanel(TrabFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtRemove.addActionListener(new TrabAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbDepartamento = new javax.swing.JLabel();
        jtxtDepartamento = new javax.swing.JTextField();
        jlbInicio = new javax.swing.JLabel();
        jlbFim = new javax.swing.JLabel();
        jlbFuncionario = new javax.swing.JLabel();
        jtxtFuncionario = new javax.swing.JTextField();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jtbTrabalho = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();
        jbtRemove = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remoção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da busca"));

        jlbDepartamento.setText("Departamento");

        jlbInicio.setText("Início");

        jlbFim.setText("Fim");

        jlbFuncionario.setText("Funcionário");

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jtxtFuncionario, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtDepartamento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                    .addComponent(jlbFuncionario, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbDepartamento, javax.swing.GroupLayout.Alignment.LEADING))
                .addGap(25, 25, 25)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jpnParamLayout.createSequentialGroup()
                            .addComponent(jlbInicio, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGap(152, 152, 152))
                        .addGroup(jpnParamLayout.createSequentialGroup()
                            .addComponent(jlbFim)
                            .addContainerGap(88, Short.MAX_VALUE)))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jftxtFim, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jftxtIni, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbDepartamento)
                    .addComponent(jlbInicio))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbFuncionario)
                    .addComponent(jlbFim))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbTrabalho.setViewportView(jtbRemove);

        jbtRemove.setText("Remover");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jtbTrabalho, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                            .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(11, 11, 11)
                .addComponent(jtbTrabalho, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addComponent(jbtRemove))
        );
    }// </editor-fold>//GEN-END:initComponents
    /*
     * Método para pegar os dados das tabelas a serem exibidas e colocá-los nas JTables
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTable();
        } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações da tabela.");
           frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Método para controlar os eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbRemove.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jbtRemove;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDepartamento;
    private javax.swing.JLabel jlbFim;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbInicio;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JScrollPane jtbTrabalho;
    private javax.swing.JTextField jtxtDepartamento;
    private javax.swing.JTextField jtxtFuncionario;
    // End of variables declaration//GEN-END:variables

    
    /*
     * Formata a tabela trabalho para ser exibida
     */
    public void setupTable() throws SQLException {

        String [] fields  = {"trabalho.idFu","funcionario.nomeCompletoFu", "trabalho.idDe","departamento.nomeDe"
            , "trabalho.dataInicioTr", "trabalho.dataFimTr"
        };
        String [] params = {"funcionario.idFu = trabalho.idFu",
            "departamento.idDe = trabalho.idDe"
        };
        String [] titles = {"ID Funcionario","Funcionario", "ID departamento", 
        "Departamento", "Data de inicio", "Data de fim" };

        String [][] result = dbInterface.view(fields,params,new String[]{"trabalho","funcionario","departamento"});

        DefaultTableModel model = new DefaultTableModel(result,titles);

        jtbRemove.setModel(model);

    }

    class TrabAction implements ActionListener {

        /*
         * Controla os eventos da remoção
         */
        public void actionPerformed(ActionEvent e) {
            ArrayList<String> param = new ArrayList<String>();

                if (jtxtFuncionario.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idFu"},
                        new String[]{"UPPER(funcionario.nomeCompletoFu)=UPPER('" + jtxtFuncionario.getText() + "')"},
                        new String[]{"funcionario"});
                        param.add("trabalho.idFu="+s[0][0]);
                    } catch (SQLException ex) {
                    }
                }
                if (jtxtDepartamento.getText().trim().compareTo("") != 0) {
                    try {
                        String[][] s = dbInterface.view(new String[]{"idDe"},
                        new String[]{"UPPER(departamento.nomeDe)=UPPER('" + jtxtDepartamento.getText() + "')"},
                        new String[]{"departamento"});
                        param.add("trabalho.idDe="+s[0][0]);
                    } catch (SQLException ex) {
                    }
                }
                if (jftxtIni.getText().compareTo("  -  -    ") != 0) {
                    param.add("trabalho.dataInicioTr="+"TO_DATE('"+jftxtIni.getText()+"','DD-MM-YYYY')");
                }
                if (jftxtFim.getText().compareTo("  -  -    ") != 0) {
                    param.add("trabalho.dataFimTr="+"TO_DATE('"+jftxtFim.getText()+"','DD-MM-YYYY')");
                }

                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"trabalho"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                } else {

                    if (jtbRemove.getSelectedRowCount() > 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String s = jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 4).toString();
                            s = s.substring(0, 10);
                            String[] params = new String[3];
                            params[0] = "idFu=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            params[1] = "idDe="+ jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 2);
                            params[2] = "trabalho.dataInicioTr=TO_DATE('"+s+"','YYYY-MM-DD')";
                            dbInterface.remove(params, new String[]{"trabalho"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }
                }
                
                try {
                setupTable();
                } catch (SQLException ex) {
                    frame.printException(ex);
                }

        }

    }

}
